package com.gxnu.edu.cn.client.clientConfig;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxnu.edu.cn.client.controller.UserClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Configuration
public class ClientConfig {
    @Bean
    public RestTemplate restTemplate() {

            RestTemplate restTemplate = new RestTemplate();

            // 配置消息转换器，强制使用 UTF-8
            List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
            for (HttpMessageConverter<?> converter : converters) {
                if (converter instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
                }
                if (converter instanceof MappingJackson2HttpMessageConverter) {
                    MappingJackson2HttpMessageConverter jsonConverter =
                            (MappingJackson2HttpMessageConverter) converter;

                    // 配置 ObjectMapper
                    ObjectMapper objectMapper = new ObjectMapper();
                    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
                    jsonConverter.setObjectMapper(objectMapper);
                }
            }

            return restTemplate;
        }
    }

